package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 查看购物车功能
     * @param userId
     * @return
     */
    @Override
    public R<List<ShoppingCart>> list(Long userId) {

        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(userId);

        return R.success(shoppingCarts);
    }


    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {

        //查找购物车表返回购物车对象
        ShoppingCart shoppingCart1 = shoppingCartMapper.findUidAndDidOrSid(shoppingCart);

        //判断,如果购物车表里无数据,则新建数据,有则加1
        if (shoppingCart1 == null) {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartMapper.add(shoppingCart);
            shoppingCart1 = shoppingCart;
        }else {
            shoppingCart1.setNumber(shoppingCart1.getNumber()+1);
            shoppingCartMapper.update(shoppingCart1);
        }


        return shoppingCart1;
    }

    /**
     * 清空购物车功能
     * @param userId
     */
    @Override
    public void clean(Long userId) {
        //直接表数据清空
        shoppingCartMapper.clean(userId);
    }

    /**
     * 根据菜品Id减少菜品
     * @param dishId
     */
    @Override
    public void updateNumberByDishId(String dishId) {
        ShoppingCart shoppingCart = shoppingCartMapper.findByDishId(dishId);
        while (true){
            //如果大于一则减少,反之则删除数据
            if (shoppingCart.getNumber()>1){
                int number = shoppingCart.getNumber()-1;
                shoppingCart.setNumber(number);
                shoppingCartMapper.update(shoppingCart);
                return;
            }else {
                shoppingCartMapper.deleteByDishId(dishId);
                return;
            }
        }
    }

    /**
     * 根据套餐Id减少套餐
     * @param setmealId
     */
    @Override
    public void updateNumberBySetmealId(String setmealId) {
        ShoppingCart shoppingCart = shoppingCartMapper.findBySetmealId(setmealId);
        while (true){
            if (shoppingCart.getNumber()>1){
                int number = shoppingCart.getNumber()-1;
                shoppingCart.setNumber(number);
                shoppingCartMapper.update(shoppingCart);
                return;
            }else {
                shoppingCartMapper.deleteBySetmealId(setmealId);
                return;
            }
        }

    }
}
